package it.wyx.kafkaclients.consumer.group;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

/**
 * 独立消费者案例（订阅主题）
 * @author wyx
 * @version V 1
 * @Date 2022/10/30
 */
public class Consumer03SubscribeTopic {
	private static final String BROKER_LIST = "localhost:9092";
	private static final String TOPIC = "test-topic";
	private static final String GROUP_ID = "test-group";

	public static void main(String[] args) {
		// 1.创建消费者的配置对象
		Properties properties = new Properties();
		properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, BROKER_LIST);
		properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
		properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
		// 设置消费者组
		properties.put(ConsumerConfig.GROUP_ID_CONFIG, GROUP_ID);

		// 2、创建消费者客户端实例
		KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);

		// 3、注册要消费的主题(可以消费多个主题)
		consumer.subscribe(Collections.singletonList(TOPIC));

		// 4、拉取数据打印
		while (true) {
			// 设置 1s 中消费一批数据
			ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(5000));
			System.out.println("接收消费records");
			for (ConsumerRecord<String, String> record : records) {
				System.out.println(record);
			}
		}
	}
}
